package com.beatles.java_nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;


/**
 * 基本通道
 * 
 * @author loong
 * @CreateTime 2018年5月2日 下午4:48:00 从一个文件复制 另一个文件
 */
public class ChannelDemo {

	public static void main(String[] args) throws IOException {

		String relativelyPath = System.getProperty("user.dir");
		System.out.println(relativelyPath);
		FileInputStream input = new FileInputStream(relativelyPath + "/testin.txt");
		//文件通道用于文件读取数据
		ReadableByteChannel source = input.getChannel();
		FileOutputStream output = new FileOutputStream(relativelyPath + "/testout.txt");
		
		WritableByteChannel destination = output.getChannel();
		copyData(source, destination);
		source.close();
		destination.close();
		System.out.println("Copy data finished");

	}
	private static void copyData(ReadableByteChannel src,WritableByteChannel dest) throws IOException {
		ByteBuffer buffer=ByteBuffer.allocateDirect(20*1024);
		while(src.read(buffer)!=-1) {
			buffer.flip();
			while(buffer.hasRemaining()) {
				dest.write(buffer);
			}
			buffer.clear();
		}
	}
}
